//
//  UserCenterController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/12.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "UserCenterController.h"

//用户信息
#import "UserInfoController.h"
//我的钱包
#import "BCWalletController.h"
//我的项目
#import "BCProjectsController.h"
//安全中心
#import "BCSafeCenterController.h"
//意见反馈
#import "BCFeedbackController.h"
#import "BCCustomerServiceController.h"
//设置中心
#import "BCSettingCenterController.h"
//
#import "BCSVIPController.h"

//分享有奖
#import "BCUserCenterShareButton.h"
#import "BCShareRewardController.h"


//用户中心headerView
#import "BCUserCenterHeaderView.h"
//centerCell
#import "BCUserCenterCell.h"

//用户中心数据model
#import "BCUserCenterModel.h"

//refresh
#import "BCRefreshNormalHeader.h"

//
#import "GSCommonLoginViewController.h"

//request
#import "BCUserCenterRequest.h"//请求用户中心数据
#import "BCUserSafeCenterRequest.h"
#import "BCUserWalletRequest.h"

#import "BCAppVersionManager.h"

@interface UserCenterController () <UITableViewDataSource,UITableViewDelegate,BCUserCenterHeaderViewDelegate> {
    BOOL _hasRequestAll;//说明已经请求了一次全部数据
    //dataSource
    BCUserCenterModel *_svip;
    BCUserCenterModel *_wallet;
    BCUserCenterModel *_projects;
    BCUserCenterModel *_safeCenter;
    BCUserCenterModel *_feedback;
}

/**
 *shareButton
 */
@property (nonatomic, strong) BCUserCenterShareButton *shareButton;

//table
@property (nonatomic, strong) UITableView *centerTable;

/**
 *BCUserCenterHeaderView
 */
@property (nonatomic, strong) BCUserCenterHeaderView *headerView;

/**
 *refreshHeader
 */
@property (nonatomic, strong) BCRefreshNormalHeader *refreshHeader;


/**
 *数据源
 */
@property (nonatomic, strong) NSMutableArray *centerSource;

/**
 *BCUserCenterData
 */
@property (nonatomic, strong) BCUserCenterData *centerData;



@end

@implementation UserCenterController

- (BCUserCenterHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[BCUserCenterHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, [BCUserCenterHeaderView defaultHeight])];
        _headerView.delegate = self;
    }
    return _headerView;
}

- (BCUserCenterShareButton *)shareButton {
    if (!_shareButton) {
        _shareButton = [BCUserCenterShareButton new];
        [_shareButton setImage:LOAD_IMAGE(@"user_center_share") forState:UIControlStateNormal];
        _shareButton.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 20, 10);
        [self.view addSubview:_shareButton];
        [_shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view).offset(10.0);
            make.top.mas_equalTo(Height_StatusBar+12.0);
        }];
        //
        [_shareButton addTarget:self action:@selector(shareButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shareButton;
}

- (NSMutableArray *)centerSource {
    if (!_centerSource) {
//        _centerSource = [NSMutableArray arrayWithArray:[BCUserCenterModel userCenterSource]];
        _centerSource = [NSMutableArray array];
    }
    return _centerSource;
}

- (BCRefreshNormalHeader *)refreshHeader {
    if (!_refreshHeader) {
        _refreshHeader = [BCRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeaderAction)];
        _refreshHeader.animateCircleClolor = [UIColor darkSubMainColor];
    }
    return _refreshHeader;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self.customNaviBar.leftButton setImage:nil forState:UIControlStateNormal];
    self.customNaviBar.backgroundColor = [UIColor darkMainColor];
    [self setupSubviews];
    
    //
    [self.centerTable addObserver:self forKeyPath:NSStringFromSelector(@selector(contentOffset)) options:NSKeyValueObservingOptionNew context:nil];
    
    //请求数据
    [self requestUserCenterDataInit:true refresh:false];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //
    if (_shareButton) {
        [self.view bringSubviewToFront:_shareButton];
    }
    
    //
    //是否用户登录了
    BOOL isLogin = [BCUserManager sharedUser].isLogin;
    //
    if (isLogin) {
        if (self.centerData&&!self.centerData.user) {
            [self.refreshHeader beginRefreshing];
        }
    }else {
        if (self.centerData.user) {
            self.centerData.user = nil;
        }
    }
    //
    if (isLogin&&!_hasRequestAll) {
        [self requestAllCenterData];
    }else {
        _hasRequestAll = false;
    }
    [self.headerView reloadData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //检测用户是否设置了指纹登录
//    [self checkUserSetLocalAuthcation];
}


- (void)setupSubviews {
    //
//    [self.customNaviBar.rightButton setTitle:BCLocalizedKey(@"uc_settings") forState:UIControlStateNormal];
    //
    self.centerTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.centerTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.centerTable.dataSource = self;
    self.centerTable.delegate = self;
    [self.view addSubview:self.centerTable];
    [self.centerTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.left.bottom.right.mas_equalTo(self.view);
    }];
    //
    [self.centerTable setTableHeaderView:self.headerView];
    //
    [self.centerTable registerClass:BCUserCenterCell.class forCellReuseIdentifier:NSStringFromClass(BCUserCenterCell.class)];
    //
//    [self.centerTable setMj_header:self.refreshHeader];
    [self.view layoutIfNeeded];
}
//KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(contentOffset))]) {
//        [self.headerView contentOffsetChanged:self.centerTable.contentOffset];
    }
}

- (void)didClickedNaviRightButton {
    [self toSettingCenterAction];
}

#pragma mark - BCUserCenterHeaderViewDelegate
- (void)userCenterHeaderViewClickedToUserInfoAction {
    if ([BCUserManager sharedUser].isLogin) {
        [self toUserInfoAction];
    }else {
        [self toLoginAction];
    }
}

#pragma mark - shareButtonDidClickedAction
/**
 分享有奖
 */
- (void)shareButtonDidClickedAction {
    if ([BCUserManager sharedUser].isLogin) {
        [BCShareRewardController showFromController:self.navigationController];
    }else {
        [GSCommonLoginViewController presentToCommloginController:self.navigationController];
    }
}

#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y>0) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.centerSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCUserCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCUserCenterCell.class)];
    cell.centerModel = self.centerSource[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BCUserCenterModel *model = self.centerSource[indexPath.row];
    
    //需要先判断是否登录的cell
    switch (model.type) {
        case BCUserCenterTypeSVIP:
        case BCUserCenterTypeWallet:
        case BCUserCenterTypeProjects:
        case BCUserCenterTypeSafeCenter:
        {
            if (![BCUserManager sharedUser].isLogin) {
                [self toLoginAction];
                return;
            }
        }
        default:
            break;
    }
    //
    switch (model.type) {
        case BCUserCenterTypeSVIP:
        {
            [self toSVIPAction];
        }
            break;
        case BCUserCenterTypeWallet:
        {
            [self toWalletAction];
        }
            break;
        case BCUserCenterTypeProjects:
        {
            [self toProjectsAction];
        }
            break;
        case BCUserCenterTypeSafeCenter:
        {
            [self toSafeCenterAction];
        }
            break;
        case BCUserCenterTypeFeedback:
        {
            [self toFeedbackAction];
        }
            break;
        case BCUserCenterTypeSettingCenter:
        {
            [self toSettingCenterAction];
        }
            break;
        default:
            break;
    }
}
#pragma mark - to action
/**
 跳转去用户中心
 */
- (void)toUserInfoAction {
    UserInfoController *userInfoVC = [UserInfoController new];
    userInfoVC.centerData = self.centerData;
    [self.navigationController pushViewController:userInfoVC animated:true];
}
/**
 跳转去我的钱包
 */
- (void)toWalletAction {
    BCWalletController *wallet = [BCWalletController new];
    [self.navigationController pushViewController:wallet animated:true];
}
/**
 跳转去我的项目
 */
- (void)toProjectsAction {
    BCProjectsController *wallet = [BCProjectsController new];
    [self.navigationController pushViewController:wallet animated:true];
}
/**
 跳转去安全中心
 */
- (void)toSafeCenterAction {
    BCSafeCenterController *wallet = [BCSafeCenterController new];
    [self.navigationController pushViewController:wallet animated:true];
}
/**
 跳转去意见反馈
 */
- (void)toFeedbackAction {
    BCFeedbackController *help = [BCFeedbackController new];
    help.helpUrl = self.centerData.tickling;
    [self.navigationController pushViewController:help animated:true];
}
/**
 跳转去设置中心
 */
- (void)toSettingCenterAction {
    BCSettingCenterController *settingCenter = [BCSettingCenterController new];
    settingCenter.centerData = self.centerData;
    [self.navigationController pushViewController:settingCenter animated:true];
}
/**
 跳转去SVIP
 */
- (void)toSVIPAction {
    BCSVIPController *svip = [BCSVIPController new];
    [self.navigationController pushViewController:svip animated:true];
}

/**
 跳转去登录
 */
- (void)toLoginAction {
    [GSCommonLoginViewController presentToCommloginController:self.navigationController];
}

#pragma mark - refreshHeaderAction
- (void)refreshHeaderAction {
    [self requestUserCenterDataInit:false refresh:true];
}
//请求个人中心数据
- (void)requestUserCenterDataInit:(BOOL)init refresh:(BOOL)refresh {
    if (init) {
        [self.view bc_showLoadingInsets:UIEdgeInsetsMake(CGRectGetHeight(self.customNaviBar.frame), 0, 0, 0)];
        self.centerTable.alpha = 0;
    }
    BCUserCenterRequest *request = [BCUserCenterRequest new];
    WEAK_SELF
    [request didRequestCompleted:^{
        if (init) {
            [wself.view bc_hiddenLoading];
        }
        if (refresh) {
            [wself.refreshHeader endRefreshing];
        }
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserCenterResponse *resp = result;
        [self handleUserCenterData:resp.data init:init refresh:refresh];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (init&&wself.view) {
//            NSString *errMsg = error.domain;
            [wself.view bc_showWithInsets:UIEdgeInsetsMake(CGRectGetHeight(self.customNaviBar.frame), 0, 0, 0) error:error needRefresh:true refreshTitle:nil target:wself refreshAction:@selector(requestInitFailedAction)];
        }
    }];
    [request requestServer];
}
- (void)requestInitFailedAction {
    [self.view bc_hiddenError];
    [self requestUserCenterDataInit:true refresh:false];
}

- (void)handleUserCenterData:(BCUserCenterData *)respData init:(BOOL)init refresh:(BOOL)refresh {
    self.centerData = respData;
    if (respData) {
        //是否显示正常UI
        BOOL normalUI = [BCAppVersionManager sharedManager].showNormalUI;
        //
        if (self.centerTable.alpha!=1) {
            self.centerTable.alpha = 1;
        }
        if (self.shareButton.alpha!=1) {
            self.shareButton.alpha = 1;
        }
        
        if (!self.centerTable.mj_header) {
            [self.centerTable setMj_header:self.refreshHeader];
            [self.centerTable bringSubviewToFront:self.centerTable.mj_header];
        }
        //navi
        [self.customNaviBar.rightButton setTitle:respData.flow.setting forState:UIControlStateNormal];
        //header
        self.headerView.centerData = respData;
        //
        self.shareButton.customTitleLabel.text = respData.flow.left;
        self.shareButton.alpha = normalUI?1:0;
    
        [self.centerSource removeAllObjects];
        //svip
        if (!_svip) {
            _svip = [BCUserCenterModel svip];
        }
        NSString *svip = respData.flow.svip;
        _svip.title = svip;
        if (svip.length) {
            if (![self.centerSource containsObject:_svip]) {
                [self.centerSource addObject:_svip];
            }
        }
        //wallet
        if (!_wallet) {
            _wallet = [BCUserCenterModel wallet];
        }
        NSString *wallet = respData.flow.wallet;
        _wallet.title = wallet;
        if (wallet.length) {
            if (![self.centerSource containsObject:_wallet]) {
                [self.centerSource addObject:_wallet];
            }
        }
        //projects
        if (normalUI) {
            if (!_projects) {
                _projects = [BCUserCenterModel projects];
            }
            NSString *project = respData.flow.project;
            _projects.title = project;
            if (project.length) {
                if (![self.centerSource containsObject:_projects]) {
                    [self.centerSource addObject:_projects];
                }
            }
        }
        //safeCenter
        if (!_safeCenter) {
            _safeCenter = [BCUserCenterModel safeCenter];
        }
        NSString *security = respData.flow.security;
        _safeCenter.title = security;
        if (security.length) {
            if (![self.centerSource containsObject:_safeCenter]) {
                [self.centerSource addObject:_safeCenter];
            }
        }
        //feedback
        if (!_feedback) {
            _feedback = [BCUserCenterModel feedback];
        }
        NSString *tickingTitle = respData.flow.tickling;
        _feedback.title = tickingTitle;
        if (tickingTitle.length) {
            if (![self.centerSource containsObject:_feedback]) {
                [self.centerSource addObject:_feedback];
            }
        }
    }
    [self.centerTable reloadData];
}

#pragma mark - 请求一次个人中心数据 失败就算了
- (void)requestAllCenterData {
    _hasRequestAll = true;
    //我的钱包
    [self requestWalletData];
    //安全中心
    [self requestSafeCenterData];
}
/**
 请求我的钱包数据
 */
- (void)requestWalletData {
    BCUserWalletRequest *request = [BCUserWalletRequest new];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserWalletResponse *resp = result;
        [BCUserManager sharedUser].walletData = resp.data;
    }];
    [request requestServer];
}
/**
 请求安全中心数据
 */
- (void)requestSafeCenterData {
    BCUserSafeCenterRequest *request = [BCUserSafeCenterRequest new];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserSafeCenterResponse *resp = result;
        [BCUserManager sharedUser].safeCenterData = resp.data;
    }];
    [request requestServer];
}

//登录状态发生变化
- (void)userLoginSuccessedAction:(NSNotification *)noti {
    [self requestUserCenterDataInit:false refresh:true];
}


#pragma mark - 提示用户设置指纹登录
/**
 每次启动提示一次就OK
 */
- (void)checkUserSetLocalAuthcation {
    if ([BCUserManager sharedUser].isLogin) {
        
        WEAK_SELF
        NSString *title = @"设置人脸识别登录";
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
        //立即设置
        NSString *settingNowTitle = @"立即设置";
        UIAlertAction *settingNowAction = [UIAlertAction actionWithTitle:settingNowTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [wself toSafeCenterAction];
        }];
        [alertVC addAction:settingNowAction];
        //稍后设置
        NSString *settingLaterTitle = @"稍后设置";
        UIAlertAction *settingLaterAction = [UIAlertAction actionWithTitle:settingLaterTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:settingLaterAction];
        //不再提示
        NSString *noLongerReminderTitle = @"不再提示";
        UIAlertAction *noLongerReminderAction = [UIAlertAction actionWithTitle:noLongerReminderTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:noLongerReminderAction];
        //
        [self.navigationController presentViewController:alertVC animated:true completion:nil];
    }
}

- (void)dealloc {
    [self.centerTable removeObserver:self forKeyPath:NSStringFromSelector(@selector(contentOffset))];
}

@end
